import { Injectable, Output, Input } from '@angular/core'
import { DatePipe } from '@angular/common'
import { FeathersService } from 'app/api/feathers.service'
// tslint:disable-next-line:import-blacklist
import * as Rx from 'rxjs'
import Push from 'app/api/model/Push'

@Injectable()
export class PushService {
  public service: any
  private dataList: Rx.BehaviorSubject<Push[]>
  num: number

  constructor(
    private feathers: FeathersService
  ) {
    this.dataList = new Rx.BehaviorSubject<Push[]>([])
    this.service = this.feathers.client.service('database/push')

    this.service.on('created', () => this.updateDataList())
    this.service.on('updated', () => this.updateDataList())
    this.service.on('patch', () => this.updateDataList())
    this.service.on('removed', () => this.updateDataList())
  }

  getDataList(): Rx.Observable<Push[]> {
    this.updateDataList()
    return this.dataList
  }

  removeData(data: Push): Promise<any> {
    return this.service.remove(data.id)
  }

  addData(data: Push): Promise<any> {
    const params: any = {
      ...{
        content: data.view_type,
        create_time: 1481624032,
        is_deleted: 0,
        is_system: true,
        status: false,
        summary: '',
        title: '',
        update_time: 0
      },
      ...data,
    }
    return this.service.create(params)
  }
  changeData(data: Push): Promise<any> {
    const params: any = {
      ...{
        content: data.title,
        create_time: 1481624032,
        is_deleted: 0,
        is_system: true,
        status: false,
        summary: '',
        title: '',
        update_time: 0
      },
      ...data,
    }
    return this.service.update(data.id, params)
  }
  private updateDataList() {
    const params = {
        query: {
          $limit: 10,
          $sort: {
            id: -1
          }
      }
    }
    this.service.find(params)
        .then((result: any) => {
          this.dataList.next(result.data)
          // result.total
          this.num = result.total
        })
        .catch((error: any) => {
          console.warn(error)
        })
    }

  }